//
//  UserViewController.m
//  SugarPile
//
//  Created by LC on 16/2/7.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "UserViewController.h"
#import "UserModel.h"
#import "UserCollectionViewCell.h"
#import "UserCollectionReusableView.h"
#import "HotDetailsViewController.h"
#import "User.h"
#import "DvdDetailsViewController.h"
@interface UserViewController ()< UICollectionViewDataSource, UICollectionViewDelegate, pushActionDelegate, pushImgViewDelegate>
@property (nonatomic, retain) UICollectionView *collection; /**<主页面*/
@property (nonatomic, retain) NSMutableArray *dayArr; /**< 保存的日期数组 */
@property (nonatomic, retain) NSMutableDictionary *photoDic; /**< 所有的照片数据字典 */
@end

@implementation UserViewController
-(void)dealloc
{
    [_user_id release];
    [_collection release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor skyBlue];
    
    // 解析数据
    [self dataHandle];
    // 创建Collection
    [self createCollection];
    
    NSLog(@"%@", _user_id);
}
- (void)createCollection
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((WIDTH - 40 * W) / 4, (WIDTH - 40 * W) / 4);
    layout.minimumInteritemSpacing = 5 * W;
    // 列
    layout.minimumLineSpacing = 5 * W;
    // 边界
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(100, 40);

    // 创建过程类似tabelView
    self.collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor floralWhite];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.contentInset = UIEdgeInsetsMake(WIDTH, 0, 0, 0);
    User *beijing = [[User alloc] initWithFrame:CGRectMake(0, -WIDTH, WIDTH, WIDTH)];
    beijing.dic = _dic;
    beijing.delegate = self;
   
    beijing.imgDelegate = self;
    [self.collection addSubview:beijing];
    
    [self.view addSubview:_collection];
    [_collection registerClass:[UserCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    // 分区头部
    [_collection registerClass:[UserCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

}
- (void)dataHandle
{
    
    [LCAFNetWorking GETWithURL:[@"http://203.80.144.212/napi/blog/list/by_user/?platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522475567%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=68&start=0&platform_name=Android&locale=zh&limit=24&app_code=nayutas&user_id=" stringByAppendingString:[NSString stringWithFormat:@"%@", _user_id]]  completion:^(id result) {
        NSMutableArray *arr = result[@"data"][@"object_list"];
        // 初始化
        self.photoDic = [NSMutableDictionary dictionary];
        self.dayArr = [NSMutableArray array];
        // 数据解析
        for (NSDictionary *dic in arr) {
            // 创建model
            UserModel *m = [[UserModel alloc] init];
            // 将遍历到的字典转换成model类保存
            [m setValuesForKeysWithDictionary:dic];
            // 获取当前model中需要当key值的数据
            NSString *days = [m.add_datetime substringToIndex:5];
            // 创建days(key值)对应的数组
            NSMutableArray *photo = _photoDic[days];
            // 判断数组是否存在
            if(photo){
                // 存在将model类添加
                [photo addObject:m];
            }else{
                // 不存在创建新的数组
                NSMutableArray *newPhoto = [NSMutableArray array];
                // 添加model类
                [newPhoto addObject:m];
                // 把数据保存到字典中
                [_photoDic setObject:newPhoto forKey:days];
            }
            // 将所有的key值保存
            if (![_dayArr containsObject:days]) {
                [_dayArr addObject:days];
            }
           
            
        }
        NSLog(@"%@", _photoDic);
//        NSLog(@"%@", _dayArr);
        [_collection reloadData];
    }];
    
}

// 分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _dayArr.count;
}
// collection头高属性
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
        UserCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.backgroundColor = [UIColor clearColor];
        header.name.text = _dayArr[indexPath.section];
        return header;
}

// 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_photoDic[_dayArr[section]] count];
}
// 对cell复制
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UserCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    UserModel *m = _photoDic[_dayArr[indexPath.section]][indexPath.item];
    // image 图片平铺
    cell.image.contentMode = UIViewContentModeScaleAspectFill;
    cell.image.clipsToBounds = YES;

    [cell.image sd_setImageWithURL:[NSURL URLWithString:[m.path stringByReplacingOccurrencesOfString:@"_webp" withString:@""]]];
    return cell;
    
}
// 点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotDetailsViewController *hotDetailsVC = [[[HotDetailsViewController alloc] init] autorelease];
    hotDetailsVC.hidesBottomBarWhenPushed = YES;
    UserModel *m = _photoDic[_dayArr[indexPath.section]][indexPath.item];
    //    NSLog(@"%ld", _index.item );
    hotDetailsVC.detailsId = m.userID;
    [self.navigationController pushViewController:hotDetailsVC animated:YES];
}
#pragma mark - 按钮跳转到专辑页
//通过 pushActionDelegate 协议的 pushAction 方法实现
- (void)pushAction:(NSString *)str
{
    NSLog(@"ddd");
    DvdDetailsViewController *dvdVC = [[[DvdDetailsViewController alloc] init] autorelease];
    dvdVC.ID = str;
    NSLog(@"%@", str);
    [self.navigationController pushViewController:dvdVC animated:YES];
}
#pragma mark -pushImgView
- (void)pushImgViewAction:(NSString *)str
{
    NSLog(@"aaa");
//    WMEImageViewController *imgView = [[WMEImageViewController alloc] init];
//    imgView.imgStr = str;
//    [self.navigationController pushViewController:imgView animated:YES];
}

// collection

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
